<template>
  <div class="creatReport">
    <div id="luckysheet" />
    <div class="right">
      <div class="top">
        <el-tabs v-model="activeName">
          <el-tab-pane :label="$t('选择字段')" name="first">
            <el-tree ref="tree" :data="dataSetOptions" :indent="10" :props="{ children: 'children', label: 'label' }" node-key="code" @node-click="nodeClickHandle">
              <span slot-scope="{ node }" class="report-tree-node" :title="node.label">{{ node.label }}</span>
            </el-tree>
          </el-tab-pane>
          <el-tab-pane :label="$t('配置管理')" name="second">
            <el-row>
              <h3>{{ $t('查询配置') }}</h3>
              <el-col :span="24">
                <p>{{ $t('查询字段') }}</p>
                <el-select v-model="selectFieldLabel" clearable @change="selectFieldLabelChange">
                  <el-option
                    v-for="item in joinDataSetFieldOptions"
                    :key="item.code"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </el-col>
              <el-col :span="24">
                <p>{{ $t('查询条件') }}</p>
                <dict-select
                  v-model="selectKey"
                  dictionary="search_way"
                  @change="selectKeyChange"
                />
              </el-col>
              <el-col :span="24">
                <p>{{ $t('查询值') }}</p>
                <el-input v-model="selectValue" :placeholder="$t('查询值')" clearable @change="selectValueChange" />
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="bottom">
        <el-button size="small" type="primary" plain @click="preview">{{ $t('预览') }}</el-button>
        <el-button v-hasPermi="['jmf:magic:edit']" size="small" type="primary" plain @click="saveOpen = true">{{ $t('保存') }}</el-button>
      </div>
    </div>
    <el-dialog
      :title="$t('保存报表')"
      :close-on-click-modal="false"
      :visible.sync="saveOpen"
      width="30%"
    >
      <el-form ref="form" :model="form" :rules="rules" class="dataForm">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('报表名称')" prop="name">
              <el-input v-model="form.name" :placeholder="$t('报表名称')" show-word-limit maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <save-btn has-permi="jmf:magic" :cancel-func="() => { saveOpen = false }" :function="save" />
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTreeDataSet, getByDataSetCode } from '@/api/dev/jmf/jmfDataSet'
import { saveJmfReport, getJmfReport, checkFileNameUnique } from '@/api/dev/jmf/jmfReport'
export default {
  data() {
    return {
      // 数据集tree
      dataSetOptions: [],
      // 数据集字段
      dataSetFieldOptions: [],
      // 关联数据集
      joinDataSetOptions: [],
      // 关联数据集字段
      joinDataSetFieldOptions: [],
      selectKey: undefined,
      selectValue: undefined,
      selectFieldLabel: undefined,
      // 配置信息
      setting: {
        default: {}
      },
      // 不同字段不同的key 配置信息key
      settingProperty: 'default',
      form: {
        name: undefined
      },
      saveOpen: false,
      drawer: false,
      activeName: 'first',
      rules: {
        name: { required: true, message: this.$t('必填信息'), trigger: 'blur' }
      },
      // 单元格所在行号
      cell_r: 0,
      // 单元格所在列号
      cell_c: 0
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$emit('refresh')
      const _this = this
      var options
      console.log(this.$route.query.reportId)
      var language = window.localStorage.getItem('language')
      switch (language) {
        case 'zh_cn':
          language = 'zh'
          break
        case 'en_us':
          language = 'en'
          break
      }
      if (this.$route.query.reportId) {
        getJmfReport(this.$route.query.reportId).then(res => {
          options = {
            container: 'luckysheet', // 设定DOM容器的id
            lang: language, // 设定表格语言
            plugins: ['chart'],
            autoExpand: true, // 定制化内容
            forceCalculation: true, // 强制刷新公式
            showinfobar: false, // 是否显示顶部信息栏
            data: JSON.parse(res.data.reportData),
            showtoolbarConfig: { print: false },
            hook: { // 事件
              cellMousedown: function(cell, postion) {
                _this.cellMousedown(cell, postion)
              },
              cellEditBefore: function(range) {
                _this.cellEditBefore(range)
              }
            }
          }
          this.form = res.data
          window.luckysheet.create(options)
        })
      } else {
        options = {
          container: 'luckysheet', // 设定DOM容器的id
          lang: language, // 设定表格语言
          plugins: ['chart'],
          autoExpand: true, // 定制化内容
          forceCalculation: true, // 强制刷新公式
          showinfobar: false, // 是否显示顶部信息栏
          showtoolbarConfig: { print: false },
          hook: { // 事件
            cellMousedown: function(cell, postion) {
              _this.cellMousedown(cell, postion)
            }
          }
        }
        window.luckysheet.create(options)
      }
      getTreeDataSet().then(res => {
        this.dataSetOptions = res.data
      })
    })
  },
  methods: {
    // 预览
    preview() {
      const viewReportUrl = this.$router.resolve({ name: 'previewReport', query: { v: 1 }})
      var data = {
        sheetData: JSON.stringify(window.luckysheet.getAllSheets()),
        setting: this.setting
      }
      localStorage.setItem('sheetData', JSON.stringify(data))
      // this.$router.push({ name: 'previewReport', params: { sheetData: window.luckysheet.getAllSheets() }})
      window.open(viewReportUrl.href, '_blank')
    },
    save() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$nextTick(() => {
            if (!this.$route.query.reportId) {
              this.form.userId = this.$store.state.user.userId
              this.form.dirId = this.$route.query.dirId
            }
            const sheets = window.luckysheet.getAllSheets()
            sheets.forEach((item) => {
              item.luckysheet_selection_range = []
            })
            this.form.reportData = sheets
            this.form.reportData = JSON.stringify(this.form.reportData)
            this.form.type = 'report'
          })
          if (this.form.id) {
            saveJmfReport(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                // eslint-disable-next-line no-self-assign
                window.parent.location.reload()
                window.close()
                this.saveOpen = false
              } else {
                this.msgError(res.msg)
              }
            })
          } else {
           checkFileNameUnique(this.form.name, this.$route.query.dirId).then(res => {
             if (res.data) {
               saveJmfReport(this.form).then(res => {
                 if (res.code === 200) {
                   this.msgSuccess(this.$t('保存成功'))
                   // eslint-disable-next-line no-self-assign
                   window.parent.location.reload()
                   window.close()
                   this.saveOpen = false
                 } else {
                   this.msgError(res.msg)
                 }
               })
             } else {
               this.msgError(this.$t('当前文件夹下,已有同名文件'))
               this.loading = false
             }
           })
          }
        }
      })
    },
    // 点击单元格钩子函数
    cellMousedown(cell, postion) {
      console.log(cell, postion)
      this.drawer = true
      this.cell_c = postion.c
      this.cell_r = postion.r
      if (cell && cell.d) {
        const param = {
          dataSetCode: cell.d.split('.')[0]
        }
        getByDataSetCode(param).then(res => {
          this.joinDataSetFieldOptions = res.data
          this.selectFieldLabel = cell.selectFieldLabel
        })
        this.selectKey = cell.selectKey
        this.selectValue = cell.selectValue
      } else {
        this.selectKey = undefined
        this.selectValue = undefined
        this.selectFieldLabel = undefined
      }
    },
    // 修改单元格钩子函数
    cellEditBefore(range) {
      console.log(range)
      this.$nextTick(() => {
        const cell = range[0]
        console.log(cell.row_focus)
      })
    },
    nodeClickHandle(data, node) {
      console.log(data, node)
      if (node.isLeaf && node.parent.data.code) {
        this.$nextTick(() => {
          const dataSetCode = node.parent.data.code
          const dataSetFieldCode = data.code
          this.settingProperty = this.cell_c + '.' + this.cell_r + '.' + dataSetCode + '.' + dataSetFieldCode
          const param = {
            dataSetCode: dataSetCode
          }
          getByDataSetCode(param).then(res => {
            this.joinDataSetFieldOptions = res.data
          })
          window.luckysheet.setCellValue(this.cell_r, this.cell_c, { v: node.parent.data.label + '.' + data.label, m: node.parent.data.label + '.' + data.label, d: dataSetCode + '.' + dataSetFieldCode, p: node.parent.parent.data.code, v1: node.parent.data.label + '.' + data.label })
        })
      }
    },
    unique(arr) {
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i].code === arr[j].code) {
            arr.splice(j, 1)
            j--
          }
        }
      }
      return arr
    },
    selectKeyChange(val) {
      window.luckysheet.setCellValue(this.cell_r, this.cell_c, { selectKey: val })
    },
    selectValueChange(val) {
      window.luckysheet.setCellValue(this.cell_r, this.cell_c, { selectValue: val })
    },
    selectFieldLabelChange(val) {
      window.luckysheet.setCellValue(this.cell_r, this.cell_c, { selectFieldLabel: val })
    }
  }
}
</script>

<style lang='scss' scoped>
/deep/.el-tab-pane{
  .el-input__inner{
    width:200px;
  }
}
/deep/.el-tree {
  width: 98%;
  .report-tree-node{
    display: inline-block;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
